# -----------------------------------------------
# Author: yuz
# Copyright: 柠檬班
# Email: wagyu2016@163.com
# Phone&Wechat: 18173179913
# -----------------------------------------------
import hashlib

from flask import Flask, request, send_from_directory
import base64
from users import generate_users

app = Flask(__name__)
users = generate_users(100)


@app.route('/fans')
def get_fans():
    return {"msg": "success", "code": 1, "data": users}


# @app.route('/user/<int:id>')
# def get_user_by_id(id):
#     """id未加密"""
#     user = users[id - 1]
#     return {"msg": "success", "code": 1, "data": user}


@app.route('/user/<encrypted>')
def get_user_by_secret(encrypted):
    """通过密文访问， /user/MQ==,,   /user/MTAw"""
    try:
        bt = encrypted.encode()
        plain_text = base64.b64decode(bt)
        id = int(plain_text)
    except Exception as e:
        return {"msg": "error id", "code": 2, "data": ""}
    else:
        user = users[id - 1]
        return {"msg": "success", "code": 1, "data": user}


@app.route('/upload', methods=['POST'])
def upload():
    avatar = request.files.get('avatar')
    if avatar is None:
        return {"msg": "please upload a file", "code": 2, "data": ""}
    img = avatar.read()
    img_key = hashlib.md5(img).hexdigest()
    with open(f'img/{img_key}.png', 'wb') as f:
        f.write(img)
    return {"msg": "success", "code": 1, "data": img_key}


@app.route('/img/<hash>')
def img(hash):
    return send_from_directory('img', hash + '.png')


@app.route('/')
def home():
    return "hello world"


if __name__ == '__main__':
    app.run(debug=True)

# md5, 校验一致性。：
# 密码
# 版本、正版校验 md5
# 大文件，
